<template>
  <div class="tree-view">
    <!-- <pre><code>{{formatJSON(parseData)}}</code></pre> -->
    <tree-view-item :data="parseData"></tree-view-item>
  </div>
</template>

<script>

  import _ from 'lodash'
  import TreeViewItem from './tree-view-item.vue'

  export default {
    name: 'tree-view',
    props: {
      data: {
        type: Object,
        required: true
      }
    },
    computed: {
      parseData () {
        return this.transformObject(this.data, "root")
      }
    },
    methods: {
      formatJSON (data) {
        return JSON.stringify(data, true, 2)
      },      
      transformObject (objectToTransform, keyForObject) {
        return {
          key: keyForObject,
          type: 'object',
          children: this.generateChildrenFromCollection(objectToTransform)
        }
      },
      generateChildrenFromCollection (collection) {
        return _.map(collection, (value, keyOrIndex) => {
          if( this.isObject(value) ){
            return this.transformObject(value, keyOrIndex)
          }
          if( this.isArray(value) ) {
            return this.transformArray(value, keyOrIndex)
          }
          if( this.isValue(value) ) {
            return this.transformValue(value, keyOrIndex)
          }
        })
      },
      // Transformer for the Array type
      transformArray: function(arrayToTransform, keyForArray){
        return {
          key: keyForArray,
          type: "array",
          children: this.generateChildrenFromCollection(arrayToTransform)
        }
      }, 
      transformValue: function(valueToTransform, keyForValue){
        return {
          key: keyForValue,
          type: "value",
          value: valueToTransform
        }
      },
      // Helper Methods for value type detection
      isObject: function(value){
        return _.isPlainObject(value);
      },
      
      isArray: function(value){
        return _.isArray(value);
      },
      
      isValue: function(value){
        return !this.isObject(value) && !this.isArray(value);
      }      
    },
    components: {
      TreeViewItem
    }
  }
</script>